# coding=utf-8
# @Time :2023/1/4 9:02
# @File :  rebuild_onehour.py
# @Author :QiKangwei
import logging
import os
import shutil
import datetime
from api import models, utils
from api.serial import mould
from api.service import exit_prod_service
from detecter import settings

logger = logging.getLogger('django')


def rebuild_onehour(mould_code):                #这是原始的重建模函数，不要删除！
    # 停止当前连接
    current_mould = mould.CurrentMould.get_instance()
    if current_mould and current_mould.is_order_running:
        exit_prod_service(current_mould)
        logger.warning(f'工单号:{current_mould.mould_code}停止检测')

    try:
        # prod_mould = models.Mould.objects.get(mould_code=mould_code)
        current_mould = mould.CurrentMould.get_instance()
        prod_mould = current_mould.prod_mould
    except:
        return utils.R.error(f'未找到编号为{mould_code}的模具')
    mould_id = prod_mould.id
    prod_mould.sample_id = 0
    prod_mould.pos_figure = ""
    prod_mould.pos_count = 0
    prod_mould.neg_count = 0
    prod_mould.threshold = settings.DEFAULT_THRESHOLD
    prod_mould.save(force_update=True)

    sample_list = models.Sample.objects.filter(mould_id=mould_id)
    sample_list.delete()

    neg_sample_list = models.NegFigure.objects.filter(mould_id=mould_id)
    neg_sample_list.delete()

    # 保存负样本信息，方便回溯
    now = datetime.datetime.now()
    history_path = os.path.join(settings.BASE_DIR, 'data', '历史信息',
                                str(mould_code) + '__' + now.strftime("%Y-%m-%d"))
    utils.check_dir_exist(history_path)
    negative_file_path = os.path.join(settings.BASE_DIR, 'data', 'sample', mould_code,
                                      "负样本信息")
    if os.path.exists(negative_file_path):
        shutil.copytree(negative_file_path, history_path)
    # 清空文件
    file_path = os.path.join(settings.BASE_DIR, 'data', 'sample', str(mould_code))
    try:
        if os.path.exists(file_path):
            shutil.rmtree(file_path)
    except Exception as e:
        logger.warning('临时更改机台号所导致：{}'.format(e))
    logger.info(f'编号为{mould_code}的模具可以重新建模了')
    a = "123456"
    b = "bash /home/whhd/start.sh"
    os.system("echo %s|sudo -S %s" % (a, b))
    logger.info('重新开启python！')
    return utils.R.ok(f'编号为{mould_code}的模具可以重新建模了')

# def rebuild_onehour(file_path,mould_code):
#     '''
#     由于重启会导致前两模数据丢失，重启次数越多，丢失的数据就越多。目前，先不采用上面的重启方式
#     '''
#     if os.path.exists(file_path):
#         try:
#             # 以写入模式打开文件，这将清空文件的内容
#             with open(file_path, 'w') as file:
#                 # 你可以在这里写入你想要的内容，但如果不写入任何内容，文件将被清空
#                 pass
#             logger.info('文件已被清空')
#         except Exception as e:
#             logger.info(f'清空文件 {file_path} 失败: {e}')
#     else:
#         logger.info(f'文件 {file_path} 不存在。')
#     file_path = os.path.join(settings.BASE_DIR, 'data', 'sample', str(mould_code))
#     try:
#         if os.path.exists(file_path):
#             shutil.rmtree(file_path)
#     except Exception as e:
#         logger.info('删除目录失败')